import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Tag, Modal, Form, Input, Select, message, Popconfirm, Card } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';

const { Option } = Select;
const { TextArea } = Input;

interface Role {
  id: number;
  name: string;
  code: string;
  description: string;
  permissions: string[];
  status: 'active' | 'inactive';
  createTime: string;
}

const RoleManagement: React.FC = () => {
  const [roles, setRoles] = useState<Role[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRole, setEditingRole] = useState<Role | null>(null);
  const [form] = Form.useForm();

  // 模拟权限列表
  const permissionOptions = [
    { value: 'user:read', label: '查看用户' },
    { value: 'user:write', label: '编辑用户' },
    { value: 'user:delete', label: '删除用户' },
    { value: 'role:read', label: '查看角色' },
    { value: 'role:write', label: '编辑角色' },
    { value: 'system:read', label: '查看系统设置' },
    { value: 'system:write', label: '编辑系统设置' },
    { value: 'product:read', label: '查看商品' },
    { value: 'product:write', label: '编辑商品' },
    { value: 'order:read', label: '查看订单' },
    { value: 'order:write', label: '编辑订单' },
  ];

  useEffect(() => {
    loadRoles();
  }, []);

  const loadRoles = async () => {
    setLoading(true);
    try {
      // 模拟 API 调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      const mockData: Role[] = [
        {
          id: 1,
          name: '超级管理员',
          code: 'admin',
          description: '拥有所有权限',
          permissions: permissionOptions.map(p => p.value),
          status: 'active',
          createTime: '2023-01-01',
        },
        {
          id: 2,
          name: '用户管理员',
          code: 'user_manager',
          description: '管理用户相关权限',
          permissions: ['user:read', 'user:write', 'user:delete'],
          status: 'active',
          createTime: '2023-01-02',
        },
        {
          id: 3,
          name: '只读用户',
          code: 'viewer',
          description: '只能查看数据',
          permissions: ['user:read', 'role:read', 'system:read'],
          status: 'active',
          createTime: '2023-01-03',
        },
      ];
      setRoles(mockData);
    } catch (error) {
      message.error('加载角色列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setEditingRole(null);
    setModalVisible(true);
    form.resetFields();
  };

  const handleEdit = (role: Role) => {
    setEditingRole(role);
    setModalVisible(true);
    form.setFieldsValue({
      ...role,
      permissions: role.permissions,
    });
  };

  const handleDelete = async (id: number) => {
    try {
      // 模拟删除
      await new Promise(resolve => setTimeout(resolve, 500));
      setRoles(roles.filter(role => role.id !== id));
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingRole) {
        // 更新角色
        const updatedRoles = roles.map(role =>
          role.id === editingRole.id
            ? { ...role, ...values }
            : role
        );
        setRoles(updatedRoles);
        message.success('更新成功');
      } else {
        // 添加角色
        const newRole: Role = {
          id: Math.max(...roles.map(r => r.id)) + 1,
          ...values,
          createTime: new Date().toISOString().split('T')[0],
        };
        setRoles([...roles, newRole]);
        message.success('添加成功');
      }
      setModalVisible(false);
    } catch (error) {
      message.error('操作失败');
    }
  };

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '角色代码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '权限数量',
      key: 'permissionCount',
      render: (_: any, record: Role) => (
        <Tag color="blue">{record.permissions.length} 个权限</Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '激活' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Role) => (
        <Space size="middle">
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定删除这个角色吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            添加角色
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={roles}
          rowKey="id"
          loading={loading}
        />
      </Card>

      <Modal
        title={editingRole ? '编辑角色' : '添加角色'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            label="角色名称"
            name="name"
            rules={[{ required: true, message: '请输入角色名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="角色代码"
            name="code"
            rules={[{ required: true, message: '请输入角色代码' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="描述"
            name="description"
          >
            <TextArea rows={3} />
          </Form.Item>

          <Form.Item
            label="权限"
            name="permissions"
            rules={[{ required: true, message: '请选择权限' }]}
          >
            <Select mode="multiple" placeholder="请选择权限">
              {permissionOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Option value="active">激活</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingRole ? '更新' : '添加'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default RoleManagement;